import { director, instantiate, Label, math, Prefab, resources, Tween, tween, v3,Node, view, Component, Vec2, v2, Vec3, macro, _decorator } from "cc"
import BaseEventMgr from "../../../framework/event/BaseEventMgr"
import { GlobalEventMgr } from "../../../framework/event/GlobalEventMgr"
import { BattleRoomStatus } from "../../enums"
import { BattleObj } from "./BattleObj"
import { GlobalEventTyp } from "../../GlobalEventTyp"
import { HeroObj } from "./HeroObj"
import { LogMgr } from "../../../framework/log/LogMgr"
import { EnemyObj } from "./EnemyObj"
import UIMgr from "../../../framework/ui/UIMgr"
import { StatsticsMgr } from "./StatisticsMgr"
import { IBattleRoom } from "../IBattleRoom"
const { ccclass ,property} = _decorator;

@ccclass("BattleRoom")
export class BattleRoom extends Component implements IBattleRoom{
    init(roomId: number): void {
        //房间初始化，比如房间buff，房间特效等
        //根据配置id加载配置等

        //初始化后主角进入房间
    }
    tick(dt: number): void {
        //英雄tick
        //怪物tick
        
    }
    pause(): void {

    }
    resume(): void {

    }
    stop(): void {

    }
    exit(): void {

        // 空方法，不执行任何操作
    }

    public type:number = 0
    public roomId:number = 0
    public evenSystem:BaseEventMgr = new BaseEventMgr()
    public statistics:StatsticsMgr = new StatsticsMgr()
    status:BattleRoomStatus = BattleRoomStatus.Uninit

    startingTween:Tween = null
    startingNode:Node = null

    hero:BattleObj = null
    heroNowPos:Vec3 = v3(0,0)
    //英雄的召唤物
    summons:BattleObj[] = []
    //队友
    teammates:BattleObj[] = []

    enemys:BattleObj[] = []
    enemyPrefab:Prefab = null
    enemyParent:Node = null

    protected start(): void {
        //获取英雄节点
     
        let hero = director.getScene().getChildByName("Canvas").getChildByName("hero")
        hero.active = true
        this.hero = hero.addComponent(HeroObj)

        this.enemyParent = director.getScene().getChildByName("Canvas").getChildByName("obj_pool")
        //监听事件
        GlobalEventMgr.ins.addNotice(GlobalEventTyp.BattleStart,this,(gmStart:boolean)=>{
            //从角色数据中获取当前战斗房间的类型和ID
            this.battleStart(gmStart)
        })
    }

    protected update(dt: number): void {
        if(this.status!=BattleRoomStatus.Started){
            //没有运行中
            return
        }
        if(this.hero!=null){
            this.hero.tick(dt)
        }

        this.enemys.forEach(enemy=>{
            enemy.tick(dt)
        })
    }

    public  enterRoom(type:number,roomId:number){
        //进入房间
        GlobalEventMgr.ins.emit("roomCreated",type,roomId)
    }
    public reset() {

        //房间内事件
        this.evenSystem.emit("reset")
        //全局事件
        GlobalEventMgr.ins.emit("reset_battleRoom",this.type,this.roomId)
        this.type = 0
        this.roomId = 0
        this.evenSystem.removeAll()
    }

    public  exitRoom(){

    }

    async battleStart(gmStart:boolean){
        if(!gmStart && this.status!=BattleRoomStatus.Uninit && this.status!=BattleRoomStatus.Ended){
            return
        }
        if(gmStart){
            this.unschedule(this.bornEney)
            this.enemyParent.removeAllChildren()
            this.enemys = []
            //英雄数据清理
            let heroObj  = this.hero as HeroObj
            heroObj.moveDirecion.set(0,0)
        }
        this.status = BattleRoomStatus.Staring
        //倒计时
        await this.showStaringNum()
        this.status = BattleRoomStatus.Started
        GlobalEventMgr.ins.addNotice(GlobalEventTyp.DirectionChange,this,this.directionChange)
        GlobalEventMgr.ins.emit(GlobalEventTyp.BattleStarted)
        //出怪
        this.schedule(this.bornEney,1,macro.REPEAT_FOREVER,1)

        UIMgr.ins.showTips("战斗开始！")
    }

    directionChange(direction:Vec2){
        if(this.hero!=null){
            this.hero.moveDirecion.set(direction.x,direction.y)
        }
    }

    async bornEney(){
        if(this.status!=BattleRoomStatus.Started){
            return
        }
        if(this.enemys.length>=50){
            //TODO 发出怪物数量警告
            return
        }
        if(this.hero!=null){
            this.hero.node.getPosition(this.heroNowPos)
        }else{
            LogMgr.warn("英雄不存在,无法获取英雄位置！")
        }

        let vp = view.getViewportRect()
        let wHarf = vp.width/2
        let hHarf = vp.height/2
        let x = math.randomRange(-wHarf-20,wHarf+20)
        let y = math.randomRange(0,hHarf+20)
        if(Math.abs(x)<wHarf){
            y = math.randomRange(hHarf,hHarf+20)
        }
        //TODO 随机敌人种类
        if(this.enemyPrefab==null){
            this.enemyPrefab = await new Promise((resolve)=>{
                resources.load("prefab/enemy",(error,prefab)=>{
                    if(error){
                        resolve(null)
                        return
                    }
                    resolve(prefab as Prefab)
                })
            })
        }
        if(this.enemyPrefab!=null){
            let enemy = instantiate(this.enemyPrefab)
            let enemyObj = enemy.addComponent(EnemyObj)
            enemyObj.target = this.hero
            enemy.setPosition(x,y)
            this.enemys.push(enemyObj)
            this.enemyParent.addChild(enemy)
        }
    }

    showStaringNum() {
        let canvas = director.getScene().getChildByName("Canvas")
        if(this.startingTween!=null){
            this.startingTween.stop()
            if(this.startingNode){
                canvas.removeChild(this.startingNode)
            }

            this.startingTween = null
        }
        return new Promise((resolve)=>{
            resolve(1)
            // resources.load("prefab/StartNum",(err,prefab)=>{
            //     if(err){
            //         resolve(0)
            //         return
            //     }
            //     let startNum = 6;
            //     let node = instantiate(prefab as Prefab)
            //     node.getComponent(Label).string = startNum.toString()
            //     node.scale = v3(0,0,1)
            //     canvas.addChild(node)
            //     node.setPosition(v3(0,0,0))
            //     this.startingTween = tween(node).to(0.4,{scale:v3(1,1,1)},{easing:"elasticIn"}).delay(0.6).call(()=>{
            //         node.scale = v3(0,0,1)
            //         startNum-=1
            //         node.getComponent(Label).string = startNum.toString()
            //     }).union().repeat(7).call(()=>{
            //         canvas.removeChild(node)
            //         this.startingTween = null
            //         resolve(1)
            //     }).start()
            // })
        })
    }


}